import {
  login,
  logout,
  getUserInfo
} from '_api/user'
import { setToken, getToken, setUserData } from '@/libs/util'

export default {
  state: {
    userData: '',
    token: getToken(),
    hasGetInfo: false
  },
  mutations: {
    setUserData (state, user) {
      state.userData = user
      setUserData(JSON.stringify(user))
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    }
  },
  getters: {},
  actions: {
    // 登录
    handleLogin ({ commit }, data) {
      return new Promise((resolve, reject) => {
        login(data).then(res => {
          const tempData = res.data
          commit('setToken', tempData.token)
          resolve(tempData)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ commit }) {
      return new Promise((resolve, reject) => {
        logout({}).then(() => {
          commit('setToken', '')
          commit('setAccess', [])
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo(state.token).then(res => {
            const data = res.data
            commit('setUserData', data)
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
